import {
    getPlayerData,
    storagePlayerData,
    ensureGroupAndPlayerExist,
    formatCurrency,
    getConfig,
    checkPermission
} from "../function/function.js";

import fs from 'fs';

export class Fight extends plugin {
    constructor() {
        super({
            name: '[Sm]奴隶反抗',
            dsc: '奴隶反抗',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]造反$/, fnc: 'rebellion' },
                { reg: /^[#\/]重置造反冷却$/, fnc: 'resetRebellion' },
                { reg: /^[#\/]讨伐\s*(\d+)?$/, fnc: 'attack' },
                { reg: /^[#\/]重置讨伐冷却$/, fnc: 'resetAttack' }
            ]
        });
    }
    
    /**
     * 获取用户银行数据
     * @param {Number} groupId - 群号
     * @param {Number} userId - 用户ID
     * @returns {Object} 用户银行数据
     */
    async getBankData(groupId, userId) {
        try {
            // 获取完整的玩家数据
            const userData = await getPlayerData(groupId, userId);
            
            // 如果没有bank字段或格式不正确，初始化一个空的bank对象
            if (!userData.bank || typeof userData.bank !== 'object') {
                return { balance: 0 };
            }
            
            return userData.bank;
        } catch (error) {
            logger.error('获取银行数据出错:', error);
            return { balance: 0 };
        }
    }
    
    /**
     * 保存用户银行数据
     * @param {Number} groupId - 群号
     * @param {Number} userId - 用户ID
     * @param {Object} bankData - 银行数据
     */
    async saveBankData(groupId, userId, bankData) {
        try {
            // 获取完整的玩家数据
            const userData = await getPlayerData(groupId, userId);
            
            // 更新bank字段
            userData.bank = bankData;
            
            // 保存更新后的玩家数据
            storagePlayerData(groupId, userId, userData);
            return true;
        } catch (error) {
            logger.error('保存银行数据出错:', error);
            return false;
        }
    }

    async rebellion(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        try {
            // 初始化玩家数据
            ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
            
            // 获取玩家数据
            const userData = await getPlayerData(ID[1], ID[0]);
            
            // 检查玩家是否有主人
            if (userData.master === '') {
                return e.reply([
                    segment.at(ID[0]),
                    '你没有主人，不需要造反'
                ]);
            }
            
            // 获取主人数据
            const masterId = userData.master;
            const masterData = await getPlayerData(ID[1], masterId);
            
            // 获取群成员列表
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);
            
            // 检查主人是否在群内
            if (!memberInfoList[masterId]) {
                // 如果主人已不在群内，自动解放奴隶
                userData.master = '';
                storagePlayerData(ID[1], ID[0], userData);
                return e.reply([
                    segment.at(ID[0]),
                    '你的主人已不在本群，你已自动获得自由！'
                ]);
            }
            
            // 检查造反冷却时间
            const config = getConfig();
            const currentSecond = Math.floor(Date.now() / 1000);
            const rebellionCooldown = config.fight?.rebellionCooldown || 3600 * 6; // 默认6小时
            
            if (!checkPermission(e) && currentSecond - (userData.lastRebellionTime || 0) < rebellionCooldown) {
                const remainingTime = rebellionCooldown - (currentSecond - (userData.lastRebellionTime || 0));
                return e.reply([`造反冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`]);
            }
            
            // 计算成功率 - 基于多种因素
            // 1. 基础成功率：5%
            // 2. 根据身价比例增减：奴隶身价越高，成功率越高
            // 3. 根据主人拥有的奴隶数量：主人奴隶越多，成功率越高(主人统治力分散)
            // 4. 随机因素
            
            let successRate = 0.05; // 基础成功率5%
            
            // 身价因素: 奴隶身价占主人身价的比例，最多增加25%几率
            const valueRatio = Math.min(userData.value / masterData.value, 1);
            successRate += valueRatio * 0.25;
            
            // 主人的奴隶数量因素: 每多一个奴隶增加2%的成功率，最多增加30%
            const slaveCountBonus = Math.min(masterData.slave.length * 0.02, 0.3);
            successRate += slaveCountBonus;
            
            // 随机波动因素: -10% 到 +10%
            const randomFactor = Math.random() * 0.2 - 0.1;
            successRate += randomFactor;
            
            // 确保概率在 15% 到 85% 之间
            successRate = Math.max(0.15, Math.min(0.85, successRate));
            
            // 记录造反尝试时间
            userData.lastRebellionTime = currentSecond;
            storagePlayerData(ID[1], ID[0], userData);
            
            // 获取用户银行账户数据
            const bankData = await this.getBankData(ID[1], ID[0]);
            const bankBalance = bankData?.balance || 0;
            const userTotalWealth = formatCurrency(userData.currency + bankBalance);
            
            // 决定造反是否成功
            const isSuccessful = Math.random() < successRate;
            
            if (isSuccessful) {
                // 造反成功
                // 从主人的奴隶列表中移除该奴隶
                masterData.slave = masterData.slave.filter(slave => slave !== ID[0]);
                storagePlayerData(ID[1], masterId, masterData);
                
                // 将奴隶设为自由人
                userData.master = '';
                // 为了平衡，成功后略微降低身价
                userData.value = formatCurrency(Math.max(100, userData.value * 0.9));
                storagePlayerData(ID[1], ID[0], userData);
                
                return e.reply([
                    segment.at(ID[0]), 
                    `你成功反抗了${memberInfoList[masterId]?.card || memberInfoList[masterId]?.nickname || masterId}的统治，重获自由！\n` +
                    `身价降低到了${userData.value.toFixed(2)}金币。\n` +
                    `(成功率约为${(successRate * 100).toFixed(1)}%)`
                ]);
            } else {
                // 造反失败
                // 主人获得奴隶的所有财产
                const confiscatedMoney = userTotalWealth;
                const walletLoss = userData.currency;
                const bankLoss = bankBalance;
                
                // 更新主人数据
                masterData.currency = formatCurrency(masterData.currency + confiscatedMoney);
                storagePlayerData(ID[1], masterId, masterData);
                
                // 更新奴隶数据
                userData.currency = 0;
                // 失败后身价上涨（因为很值钱）
                userData.value = formatCurrency(userData.value * 1.2);
                storagePlayerData(ID[1], ID[0], userData);
                
                // 清空银行账户
                if (bankBalance > 0) {
                    bankData.balance = 0;
                    await this.saveBankData(ID[1], ID[0], bankData);
                }
                
                let replyMsg = [
                    segment.at(ID[0]), 
                    `你试图反抗${memberInfoList[masterId]?.card || memberInfoList[masterId]?.nickname || masterId}的统治，但失败了！\n` +
                    `${memberInfoList[masterId]?.card || memberInfoList[masterId]?.nickname || masterId}没收了你所有的财产：\n` +
                    `钱包：${walletLoss.toFixed(2)}金币\n`
                ];
                
                // 如果有银行存款，显示银行被没收的部分
                if (bankLoss > 0) {
                    replyMsg[1] += `银行：${bankLoss.toFixed(2)}金币\n`;
                }
                
                replyMsg[1] += `总计：${confiscatedMoney.toFixed(2)}金币\n` +
                               `你的身价上涨到了${userData.value.toFixed(2)}金币\n` +
                               `(成功率约为${(successRate * 100).toFixed(1)}%)`;
                
                return e.reply(replyMsg);
            }
            
        } catch (error) {
            logger.error('处理造反请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }
    
    async resetRebellion(e) {
        if (!e.isMaster) return e.reply('只有主人才能重置冷却时间');
        if (!e.isGroup) return e.reply('该命令只能在群内使用');

        try {
            const groupId = e.group_id;
            const files = fs.readdirSync(`plugins/Slave-Market/data/player/${groupId}`);
            
            for (const file of files) {
                if (file.endsWith('.json')) {
                    const playerData = await getPlayerData(groupId, file.replace('.json', ''));
                    playerData.lastRebellionTime = 0;
                    storagePlayerData(groupId, file.replace('.json', ''), playerData);
                }
            }
            
            return e.reply('已重置本群所有成员的造反冷却时间');
        } catch (error) {
            logger.error('重置造反冷却时间时出错:', error);
            return e.reply('重置冷却时间时出错，请稍后再试');
        }
    }

    /**
     * 讨伐功能 - 让奴隶主向其他奴隶主发起挑战
     * @param {Object} e - 消息事件对象
     * @returns {Promise<void>}
     */
    async attack(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];
        
        try {
            // 初始化玩家数据
            ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
            
            // 获取玩家数据
            const userData = await getPlayerData(ID[1], ID[0]);
            
            // 检查玩家是否有奴隶
            if (!userData.slave || userData.slave.length === 0) {
                return e.reply([
                    segment.at(ID[0]),
                    '你不是奴隶主，无法发起讨伐'
                ]);
            }
            
            // 获取目标用户ID
            let targetId = e.msg.match(/^[#\/]讨伐\s*(\d+)?$/)?.[1];
            if (!targetId && e.at) {
                targetId = e.at;
            }
            
            if (!targetId) {
                return e.reply([
                    segment.at(ID[0]),
                    '请指定讨伐目标(@对方 或 使用 /讨伐+QQ号)'
                ]);
            }
            
            // 不能讨伐自己
            if (targetId == ID[0]) {
                return e.reply([
                    segment.at(ID[0]),
                    '你不能讨伐自己'
                ]);
            }
            
            // 初始化目标玩家数据
            ensureGroupAndPlayerExist(ID[1], targetId, '目标用户');
            
            // 获取目标玩家数据
            const targetData = await getPlayerData(ID[1], targetId);
            
            // 检查目标是否有奴隶
            if (!targetData.slave || targetData.slave.length === 0) {
                return e.reply([
                    segment.at(ID[0]),
                    '目标不是奴隶主，无法进行讨伐'
                ]);
            }
            
            // 获取群成员列表
            const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()]);
            
            // 检查目标是否在群内
            if (!memberInfoList[targetId]) {
                return e.reply([
                    segment.at(ID[0]),
                    '目标不在本群，无法进行讨伐'
                ]);
            }
            
            // 检查讨伐冷却时间
            const config = getConfig();
            const currentSecond = Math.floor(Date.now() / 1000);
            const attackCooldown = config.fight?.attackCooldown || 3600 * 12; // 默认12小时
            
            if (!checkPermission(e) && currentSecond - (userData.lastAttackTime || 0) < attackCooldown) {
                const remainingTime = attackCooldown - (currentSecond - (userData.lastAttackTime || 0));
                return e.reply([
                    segment.at(ID[0]),
                    `讨伐冷却中，剩余时间：${Math.floor(remainingTime / 3600)}小时${Math.floor((remainingTime % 3600) / 60)}分钟`
                ]);
            }
            
            // 更新讨伐时间
            userData.lastAttackTime = currentSecond;
            storagePlayerData(ID[1], ID[0], userData);
            
            // 获取用户名称
            const attackerName = memberInfoList[ID[0]]?.card || memberInfoList[ID[0]]?.nickname || ID[0];
            const defenderName = memberInfoList[targetId]?.card || memberInfoList[targetId]?.nickname || targetId;
            
            // 计算战力
            const attackerPower = await this.calculatePower(ID[1], ID[0], userData);
            const defenderPower = await this.calculatePower(ID[1], targetId, targetData);
            
            // 计算战力详细数据用于显示
            const attackerDetails = await this.getWarPowerDetails(ID[1], ID[0], userData);
            const defenderDetails = await this.getWarPowerDetails(ID[1], targetId, targetData);
            
            // 计算胜率
            const winRate = attackerPower / (attackerPower + defenderPower);
            const winRatePercentage = Math.round(winRate * 100);
            
            // 发送战力对比信息
            await e.reply([
                segment.at(ID[0]),
                `\n【战力对比】\n` +
                `▶ ${attackerName}(进攻方):\n` +
                `  总战力: ${Math.round(attackerPower)} 点\n` +
                `  - 基础战力: ${attackerDetails.base} 点\n` +
                `  - 奴隶数量加成: ${attackerDetails.slaveCount} 点\n` +
                `  - 奴隶身价加成: ${attackerDetails.slaveValue} 点\n` +
                `  - 自身身价加成: ${attackerDetails.selfValue} 点\n` +
                `  - 武器加成: ${attackerDetails.weapons} 点\n` +
                `  - 随机波动: ${attackerDetails.random}%\n\n` +
                `▶ ${defenderName}(防守方):\n` +
                `  总战力: ${Math.round(defenderPower)} 点\n` +
                `  - 基础战力: ${defenderDetails.base} 点\n` +
                `  - 奴隶数量加成: ${defenderDetails.slaveCount} 点\n` +
                `  - 奴隶身价加成: ${defenderDetails.slaveValue} 点\n` +
                `  - 自身身价加成: ${defenderDetails.selfValue} 点\n` +
                `  - 武器加成: ${defenderDetails.weapons} 点\n` +
                `  - 随机波动: ${defenderDetails.random}%\n\n` +
                `预计胜率: ${winRatePercentage}%\n` +
                `战斗即将开始...`
            ]);
            
            // 添加短暂延迟，让用户有时间看到战力对比
            await new Promise(resolve => setTimeout(resolve, 2000));
            
            // 随机结果
            const roll = Math.random();
            let outcome;
            
            // 结局类型更加丰富
            if (roll < 0.03) {
                // 3% 完败且被俘虏
                outcome = 'complete_defeat_captured';
            } else if (roll < 0.05) {
                // 2% 奇袭失败
                outcome = 'ambush_failure';
            } else if (roll < 0.10) {
                // 5% 完败
                outcome = 'complete_defeat';
            } else if (roll < 0.25) {
                // 15% 小败
                outcome = 'minor_defeat';
            } else if (roll < 0.30) {
                // 5% 平局但获得情报
                outcome = 'draw_with_intel';
            } else if (roll < 0.70) {
                // 40% 两败俱伤
                outcome = 'draw';
            } else if (roll < 0.80) {
                // 10% 背水一战逆转
                outcome = 'comeback_victory';
            } else if (roll < 0.95) {
                // 15% 小胜
                outcome = 'minor_victory';
            } else if (roll < 0.97) {
                // 2% 奇袭成功
                outcome = 'ambush_success';
            } else {
                // 3% 完胜
                outcome = 'complete_victory';
            }
            
            // 调整概率根据战力差异
            if (winRate > 0.65) { // 战力明显优势
                // 转化一些负面结局为较好结局
                if (outcome === 'complete_defeat_captured') outcome = 'minor_defeat';
                if (outcome === 'complete_defeat') outcome = 'minor_defeat';
                if (outcome === 'ambush_failure') outcome = 'draw';
                if (outcome === 'minor_defeat' && Math.random() > 0.5) outcome = 'draw';
                if (outcome === 'draw' && Math.random() > 0.7) outcome = 'minor_victory';
            } else if (winRate < 0.35) { // 战力明显劣势
                // 转化一些正面结局为较差结局
                if (outcome === 'complete_victory') outcome = 'minor_victory';
                if (outcome === 'ambush_success') outcome = 'draw';
                if (outcome === 'minor_victory' && Math.random() > 0.5) outcome = 'draw';
                if (outcome === 'draw' && Math.random() > 0.7) outcome = 'minor_defeat';
            }
            
            // 战力压倒性优势或劣势时的额外调整
            if (winRate > 0.85) {
                // 极高战力优势时提高完胜概率
                if (outcome === 'minor_victory' && Math.random() > 0.6) outcome = 'ambush_success';
                if (outcome === 'ambush_success' && Math.random() > 0.8) outcome = 'complete_victory';
            } else if (winRate < 0.15) {
                // 极高战力劣势时提高完败概率
                if (outcome === 'minor_defeat' && Math.random() > 0.6) outcome = 'ambush_failure';
                if (outcome === 'ambush_failure' && Math.random() > 0.8) outcome = 'complete_defeat_captured';
            }
            
            // 战力压倒性优势或劣势时的额外调整
            const result = await this.executeOutcome(
                outcome, 
                ID[1], 
                ID[0], 
                targetId, 
                userData, 
                targetData, 
                attackerName,
                defenderName
            );
            
            return e.reply(result);
            
        } catch (error) {
            logger.error('处理讨伐请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试。']);
        }
    }
    
    /**
     * 获取战力详细计算数据
     * @param {Number} groupId - 群号
     * @param {Number} userId - 用户ID
     * @param {Object} userData - 用户数据
     * @returns {Object} 详细战力数据
     */
    async getWarPowerDetails(groupId, userId, userData) {
        // 基础战力
        const baseWarPower = 100;
        let details = {
            base: baseWarPower,
            slaveCount: 0,
            slaveValue: 0,
            selfValue: 0,
            weapons: 0,
            random: 0,
            total: baseWarPower
        };
        
        try {
            // 1. 奴隶数量带来的战力加成，每个奴隶+15%
            const slaveCount = userData.slave?.length || 0;
            details.slaveCount = Math.round(baseWarPower * (slaveCount * 0.15));
            
            // 2. 奴隶身价带来的战力加成
            if (slaveCount > 0) {
                let totalSlaveValue = 0;
                
                // 获取所有奴隶的身价总和
                for (const slaveId of userData.slave || []) {
                    try {
                        const slaveData = await getPlayerData(groupId, slaveId);
                        totalSlaveValue += slaveData.value || 0;
                    } catch (err) {
                        logger.warn(`无法读取奴隶${slaveId}的数据，忽略此奴隶的身价`);
                    }
                }
                
                // 每5000金币奴隶身价增加1点战力
                details.slaveValue = Math.round(totalSlaveValue / 5000);
            }
            
            // 3. 自身身价增加战力，每1000金币增加1点战力
            details.selfValue = Math.round(userData.value / 1000);
            
            // 4. 从武器数据中获取战力
            // 尝试读取用户武器数据
            const dirpath2 = "../../../akasha-terminal-plugin/data/UserData";
            const filename = `${userId}.json`;
            
            try {
                if (fs.existsSync(dirpath2 + "/" + filename)) {
                    const json = JSON.parse(fs.readFileSync(dirpath2 + "/" + filename, "utf8"));
                    
                    // 获取不同等级武器数量 - 从num属性获取
                    let lowWeapons = json['3']?.num || 0;
                    let midWeapons = json['4']?.num || 0;
                    let highWeapons = json['5']?.num || 0;
                    
                    // 如果num值为0，但有武器数据，则重新计算武器总数
                    if (lowWeapons === 0 && Object.keys(json['3'] || {}).length > 1) {
                        lowWeapons = Object.keys(json['3'] || {}).filter(key => key !== 'num').length;
                    }
                    
                    if (midWeapons === 0 && Object.keys(json['4'] || {}).length > 1) {
                        midWeapons = Object.keys(json['4'] || {}).filter(key => key !== 'num').length;
                    }
                    
                    if (highWeapons === 0 && Object.keys(json['5'] || {}).length > 1) {
                        highWeapons = Object.keys(json['5'] || {}).filter(key => key !== 'num').length;
                    }
                    
                    details.weapons = (lowWeapons * 5) + (midWeapons * 10) + (highWeapons * 15);
                    
                    logger.debug(`用户${userId}武器数据: 下位武器=${lowWeapons}, 上位武器=${midWeapons}, 大师级武器=${highWeapons}, 武器战力=${details.weapons}`);
                }
            } catch (err) {
                logger.warn(`无法读取用户${userId}的武器数据，忽略此战力部分: ${err}`);
            }
            
            // 5. 随机波动 ±10%
            const randomFactor = Math.round((Math.random() * 20) - 10);
            details.random = randomFactor;
            
            // 计算总战力（不含随机波动）
            const subtotal = details.base + details.slaveCount + details.slaveValue + 
                            details.selfValue + details.weapons;
            
            // 应用随机波动
            details.total = Math.round(subtotal * (1 + randomFactor / 100));
            
            return details;
            
        } catch (error) {
            logger.error('计算详细战力时出错:', error);
            return {
                base: baseWarPower,
                slaveCount: 0,
                slaveValue: 0,
                selfValue: 0,
                weapons: 0,
                random: 0,
                total: baseWarPower
            };
        }
    }
    
    /**
     * 计算玩家战力值
     * @param {Number} groupId - 群号
     * @param {Number} userId - 用户ID
     * @param {Object} userData - 用户数据
     */
    async calculatePower(groupId, userId, userData) {
        let power = 100; // 基础战力
        
        try {
            // 1. 奴隶数量带来的战力加成，每个奴隶+15%
            const slaveCount = userData.slave?.length || 0;
            power += power * (slaveCount * 0.15);
            
            // 2. 奴隶身价带来的战力加成
            if (slaveCount > 0) {
                let totalSlaveValue = 0;
                
                // 获取所有奴隶的身价总和
                for (const slaveId of userData.slave || []) {
                    try {
                        const slaveData = await getPlayerData(groupId, slaveId);
                        totalSlaveValue += slaveData.value || 0;
                    } catch (err) {
                        logger.warn(`无法读取奴隶${slaveId}的数据，忽略此奴隶的身价`);
                    }
                }
                
                // 每5000金币奴隶身价增加1点战力
                power += totalSlaveValue / 5000;
                
                // 记录日志
                logger.debug(`[战力计算] 用户${userId}的奴隶总身价为${totalSlaveValue}，增加战力${totalSlaveValue / 5000}`);
            }
            
            // 3. 自身身价增加战力，每1000金币增加1点战力
            power += userData.value / 1000;
            
            // 4. 从武器数据中获取战力
            // 尝试读取用户武器数据
            const dirpath2 = "../../../akasha-terminal-plugin/data/UserData";
            const filename = `${userId}.json`;
            
            try {
                if (fs.existsSync(dirpath2 + "/" + filename)) {
                    const json = JSON.parse(fs.readFileSync(dirpath2 + "/" + filename, "utf8"));
                    
                    // 获取不同等级武器数量 - 从num属性获取
                    let lowWeapons = json['3']?.num || 0;
                    let midWeapons = json['4']?.num || 0;
                    let highWeapons = json['5']?.num || 0;
                    
                    // 如果num值为0，但有武器数据，则重新计算武器总数
                    if (lowWeapons === 0 && Object.keys(json['3'] || {}).length > 1) {
                        lowWeapons = Object.keys(json['3'] || {}).filter(key => key !== 'num').length;
                    }
                    
                    if (midWeapons === 0 && Object.keys(json['4'] || {}).length > 1) {
                        midWeapons = Object.keys(json['4'] || {}).filter(key => key !== 'num').length;
                    }
                    
                    if (highWeapons === 0 && Object.keys(json['5'] || {}).length > 1) {
                        highWeapons = Object.keys(json['5'] || {}).filter(key => key !== 'num').length;
                    }
                    
                    // 低级武器每个+5战力，中级武器每个+10战力，高级武器每个+15战力
                    power += (lowWeapons * 5) + (midWeapons * 10) + (highWeapons * 15);
                    
                    logger.debug(`[战力计算] 用户${userId}的武器: 下位武器=${lowWeapons}, 上位武器=${midWeapons}, 大师级武器=${highWeapons}`);
                }
            } catch (err) {
                // 如果读取失败，忽略武器系统的战力部分
                logger.warn(`无法读取用户${userId}的武器数据，忽略此战力部分: ${err}`);
            }
            
            // 5. 添加随机波动 ±10%
            power *= (0.9 + Math.random() * 0.2);
            
            return power;
            
        } catch (error) {
            logger.error('计算战力时出错:', error);
            return 100; // 出错时返回基础战力
        }
    }
    
    /**
     * 执行结局
     * @param {String} outcome - 结局类型
     * @param {Number} groupId - 群号
     * @param {Number} attackerId - 攻击者ID
     * @param {Number} defenderId - 防守者ID
     * @param {Object} attackerData - 攻击者数据
     * @param {Object} defenderData - 防守者数据
     * @param {String} attackerName - 攻击者名称
     * @param {String} defenderName - 防守者名称
     */
    async executeOutcome(
        outcome, 
        groupId, 
        attackerId, 
        defenderId,
        attackerData,
        defenderData,
        attackerName,
        defenderName
    ) {
        // 克隆数据，避免直接修改
        const attacker = JSON.parse(JSON.stringify(attackerData));
        const defender = JSON.parse(JSON.stringify(defenderData));
        
        // 获取奴隶列表并记录初始状态
        const attackerSlaves = attacker.slave || [];
        const defenderSlaves = defender.slave || [];
        const initialAttackerMoney = attacker.currency;
        const initialDefenderMoney = defender.currency;
        const initialAttackerSlaveCount = attackerSlaves.length;
        const initialDefenderSlaveCount = defenderSlaves.length;
        
        let result = [];
        
        switch (outcome) {
            case 'complete_defeat_captured':
                // 完全失败且被俘虏：损失所有财产和奴隶，并且立刻成为对方奴隶
                result = [
                    segment.at(attackerId),
                    `你的讨伐军队遭遇了致命打击，全军覆没！\n\n${defenderName}不仅击溃了你的军队，还将你本人俘虏！\n`
                ];
                
                // 转移所有财产
                defender.currency = formatCurrency(defender.currency + attacker.currency);
                attacker.currency = 0;
                
                // 转移所有奴隶
                for (const slaveId of attackerSlaves) {
                    if (!defender.slave.includes(slaveId)) {
                        defender.slave.push(slaveId);
                        
                        // 更新奴隶的主人信息
                        const slaveData = await getPlayerData(groupId, slaveId);
                        slaveData.master = defenderId;
                        storagePlayerData(groupId, slaveId, slaveData);
                    }
                }
                
                // 清空攻击者的奴隶列表
                attacker.slave = [];
                
                // 检查攻击者是否已经有主人
                if (attacker.master && attacker.master !== '') {
                    // 处理主人争夺战...（代码保持不变）
                } else {
                    // 攻击者没有主人，直接成为奴隶
                    attacker.master = defenderId;
                    
                    // 如果防守者的奴隶列表中没有攻击者，添加
                    if (!defender.slave.includes(attackerId)) {
                        defender.slave.push(attackerId);
                    }
                    
                    result[1] += `你彻底沦为了${defenderName}的奴隶！你的身价因战败而暂时降低！`;
                    
                    // 讨伐失败导致身价暂时降低
                    attacker.value = formatCurrency(attacker.value * 0.8);
                }
                
                // 添加详细的损失和收益统计
                result[1] += `\n\n【战斗结果】\n`;
                result[1] += `◆ ${attackerName}(你):\n`;
                result[1] += `  • 金币: ${initialAttackerMoney.toFixed(2)} → 0 (-${initialAttackerMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialAttackerSlaveCount} → 0 (-${initialAttackerSlaveCount})\n`;
                result[1] += `  • 额外惩罚: 你本人成为奴隶，身价降低20%\n\n`;
                result[1] += `◆ ${defenderName}:\n`;
                result[1] += `  • 金币: ${initialDefenderMoney.toFixed(2)} → ${defender.currency.toFixed(2)} (+${initialAttackerMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialDefenderSlaveCount} → ${defender.slave.length} (+${initialAttackerSlaveCount + (defender.slave.includes(attackerId) ? 1 : 0)})`;
                break;
                
            case 'minor_defeat':
                // 小败：损失一半财产和奴隶
                result = [
                    segment.at(attackerId),
                    `你的讨伐军队遭遇了挫折！\n\n${defenderName}击退了你的进攻！\n`
                ];
                
                // 计算要转移的财产
                const lostMoney = Math.floor(attacker.currency / 2);
                attacker.currency = formatCurrency(attacker.currency - lostMoney);
                defender.currency = formatCurrency(defender.currency + lostMoney);
                
                // 计算要转移的奴隶数量
                const lostSlaveCount = Math.floor(attackerSlaves.length / 2);
                
                // 随机选择要转移的奴隶
                const lostSlaves = this.getRandomElements(attackerSlaves, lostSlaveCount);
                
                // 转移奴隶
                let actualTransferredSlaves = 0;
                for (const slaveId of lostSlaves) {
                    // 从攻击者的奴隶列表中移除
                    attacker.slave = attacker.slave.filter(id => id !== slaveId);
                    
                    // 添加到防守者的奴隶列表中
                    if (!defender.slave.includes(slaveId)) {
                        defender.slave.push(slaveId);
                        actualTransferredSlaves++;
                        
                        // 更新奴隶的主人信息
                        const slaveData = await getPlayerData(groupId, slaveId);
                        slaveData.master = defenderId;
                        storagePlayerData(groupId, slaveId, slaveData);
                    }
                }
                
                // 添加详细的损失和收益统计
                result[1] += `\n【战斗结果】\n`;
                result[1] += `◆ ${attackerName}(你):\n`;
                result[1] += `  • 金币: ${initialAttackerMoney.toFixed(2)} → ${attacker.currency.toFixed(2)} (-${lostMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialAttackerSlaveCount} → ${attacker.slave.length} (-${actualTransferredSlaves})\n\n`;
                result[1] += `◆ ${defenderName}:\n`;
                result[1] += `  • 金币: ${initialDefenderMoney.toFixed(2)} → ${defender.currency.toFixed(2)} (+${lostMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialDefenderSlaveCount} → ${defender.slave.length} (+${actualTransferredSlaves})`;
                break;
                
            case 'draw':
                // 两败俱伤：双方损失部分财产和奴隶
                result = [
                    segment.at(attackerId),
                    `你的讨伐军队与${defenderName}的军队陷入了激烈的战斗！\n\n双方两败俱伤！\n`
                ];
                
                // 计算双方损失的财产
                const attackerLostMoney = Math.floor(attacker.currency / 4);
                const defenderLostMoney = Math.floor(defender.currency / 4);
                
                attacker.currency = formatCurrency(attacker.currency - attackerLostMoney);
                defender.currency = formatCurrency(defender.currency - defenderLostMoney);
                
                // 计算双方损失的奴隶数量
                const attackerLostSlaveCount = Math.floor(attackerSlaves.length / 4);
                const defenderLostSlaveCount = Math.floor(defenderSlaves.length / 4);
                
                // 随机选择双方损失的奴隶
                const attackerLostSlaves = this.getRandomElements(attackerSlaves, attackerLostSlaveCount);
                const defenderLostSlaves = this.getRandomElements(defenderSlaves, defenderLostSlaveCount);
                
                // 移除双方损失的奴隶
                let actualAttackerFreedSlaves = 0;
                for (const slaveId of attackerLostSlaves) {
                    attacker.slave = attacker.slave.filter(id => id !== slaveId);
                    actualAttackerFreedSlaves++;
                    
                    const slaveData = await getPlayerData(groupId, slaveId);
                    slaveData.master = '';
                    storagePlayerData(groupId, slaveId, slaveData);
                }
                
                let actualDefenderFreedSlaves = 0;
                for (const slaveId of defenderLostSlaves) {
                    defender.slave = defender.slave.filter(id => id !== slaveId);
                    actualDefenderFreedSlaves++;
                    
                    const slaveData = await getPlayerData(groupId, slaveId);
                    slaveData.master = '';
                    storagePlayerData(groupId, slaveId, slaveData);
                }
                
                // 添加详细的损失和收益统计
                result[1] += `\n【战斗结果】\n`;
                result[1] += `◆ ${attackerName}(你):\n`;
                result[1] += `  • 金币: ${initialAttackerMoney.toFixed(2)} → ${attacker.currency.toFixed(2)} (-${attackerLostMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialAttackerSlaveCount} → ${attacker.slave.length} (-${actualAttackerFreedSlaves})\n\n`;
                result[1] += `◆ ${defenderName}:\n`;
                result[1] += `  • 金币: ${initialDefenderMoney.toFixed(2)} → ${defender.currency.toFixed(2)} (-${defenderLostMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialDefenderSlaveCount} → ${defender.slave.length} (-${actualDefenderFreedSlaves})\n\n`;
                result[1] += `* 注: 双方脱离控制的奴隶均重获自由`;
                break;
                
            case 'minor_victory':
                // 小胜：获得部分财产和奴隶
                result = [
                    segment.at(attackerId),
                    `你的讨伐军队击败了${defenderName}的军队！\n\n你获得了胜利！\n`
                ];
                
                // 计算获得的财产
                const gainedMoney = Math.floor(defender.currency / 2);
                attacker.currency = formatCurrency(attacker.currency + gainedMoney);
                defender.currency = formatCurrency(defender.currency - gainedMoney);
                
                // 计算获得的奴隶数量
                const gainedSlaveCount = Math.floor(defenderSlaves.length / 2);
                
                // 随机选择获得的奴隶
                const gainedSlaves = this.getRandomElements(defenderSlaves, gainedSlaveCount);
                
                // 转移奴隶
                let actualGainedSlaves = 0;
                for (const slaveId of gainedSlaves) {
                    defender.slave = defender.slave.filter(id => id !== slaveId);
                    
                    if (!attacker.slave.includes(slaveId)) {
                        attacker.slave.push(slaveId);
                        actualGainedSlaves++;
                        
                        const slaveData = await getPlayerData(groupId, slaveId);
                        slaveData.master = attackerId;
                        storagePlayerData(groupId, slaveId, slaveData);
                    }
                }
                
                // 添加详细的损失和收益统计
                result[1] += `\n【战斗结果】\n`;
                result[1] += `◆ ${attackerName}(你):\n`;
                result[1] += `  • 金币: ${initialAttackerMoney.toFixed(2)} → ${attacker.currency.toFixed(2)} (+${gainedMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialAttackerSlaveCount} → ${attacker.slave.length} (+${actualGainedSlaves})\n\n`;
                result[1] += `◆ ${defenderName}:\n`;
                result[1] += `  • 金币: ${initialDefenderMoney.toFixed(2)} → ${defender.currency.toFixed(2)} (-${gainedMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialDefenderSlaveCount} → ${defender.slave.length} (-${actualGainedSlaves})`;
                break;
                
            case 'complete_victory':
                // 完胜：获得所有财产和奴隶，可能包括防守者自己
                result = [
                    segment.at(attackerId),
                    `你的讨伐军队彻底击败了${defenderName}的军队！\n\n你取得了压倒性的胜利！\n`
                ];
                
                // 转移所有财产
                const victoryGainedMoney = defender.currency;
                attacker.currency = formatCurrency(attacker.currency + defender.currency);
                defender.currency = 0;
                
                // 转移所有奴隶
                let actualVictoryGainedSlaves = 0;
                for (const slaveId of defenderSlaves) {
                    defender.slave = defender.slave.filter(id => id !== slaveId);
                    
                    if (!attacker.slave.includes(slaveId)) {
                        attacker.slave.push(slaveId);
                        actualVictoryGainedSlaves++;
                        
                        const slaveData = await getPlayerData(groupId, slaveId);
                        slaveData.master = attackerId;
                        storagePlayerData(groupId, slaveId, slaveData);
                    }
                }
                
                // 检查防守者是否成为奴隶
                let capturedDefender = false;
                
                // 检查防守者是否已经有主人
                if (defender.master && defender.master !== '') {
                    // 处理主人争夺战...（代码保持不变）
                } else if (Math.random() < 0.7) { // 70%几率成为奴隶
                    // 防守者没有主人，有几率直接成为奴隶
                    defender.slave = [];
                    defender.master = attackerId;
                    
                    // 如果攻击者的奴隶列表中没有防守者，添加
                    if (!attacker.slave.includes(defenderId)) {
                        attacker.slave.push(defenderId);
                        capturedDefender = true;
                    }
                    
                    result[1] += `\n\n由于彻底战败，${defenderName}沦为了你的奴隶！`;
                }
                
                // 添加详细的损失和收益统计
                result[1] += `\n\n【战斗结果】\n`;
                result[1] += `◆ ${attackerName}(你):\n`;
                result[1] += `  • 金币: ${initialAttackerMoney.toFixed(2)} → ${attacker.currency.toFixed(2)} (+${victoryGainedMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialAttackerSlaveCount} → ${attacker.slave.length} (+${actualVictoryGainedSlaves + (capturedDefender ? 1 : 0)})\n`;
                if (capturedDefender) {
                    result[1] += `  • 额外收获: ${defenderName}本人成为你的奴隶\n`;
                }
                result[1] += `\n◆ ${defenderName}:\n`;
                result[1] += `  • 金币: ${initialDefenderMoney.toFixed(2)} → 0 (-${victoryGainedMoney.toFixed(2)})\n`;
                result[1] += `  • 奴隶: ${initialDefenderSlaveCount} → 0 (-${initialDefenderSlaveCount})`;
                if (capturedDefender) {
                    result[1] += `\n  • 额外损失: ${defenderName}本人沦为奴隶`;
                }
                break;
                
            // 其他结局类型也需要类似改进...
        }
        
        // 保存更新后的数据
        storagePlayerData(groupId, attackerId, attacker);
        storagePlayerData(groupId, defenderId, defender);
        
        return result;
    }
    
    /**
     * 获取随机元素
     * @param {Array} array - 数组
     * @param {Number} count - 随机元素数量
     * @returns {Array} 随机元素
     */
    getRandomElements(array, count) {
        const shuffled = array.slice();
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled.slice(0, count);
    }
    
    async resetAttack(e) {
        if (!e.isMaster) return e.reply('只有主人才能重置冷却时间');
        if (!e.isGroup) return e.reply('该命令只能在群内使用');

        try {
            const groupId = e.group_id;
            const files = fs.readdirSync(`plugins/Slave-Market/data/player/${groupId}`);
            
            for (const file of files) {
                if (file.endsWith('.json')) {
                    const playerData = await getPlayerData(groupId, file.replace('.json', ''));
                    playerData.lastAttackTime = 0;
                    storagePlayerData(groupId, file.replace('.json', ''), playerData);
                }
            }
            
            return e.reply('已重置本群所有成员的讨伐冷却时间');
        } catch (error) {
            logger.error('重置讨伐冷却时间时出错:', error);
            return e.reply('重置冷却时间时出错，请稍后再试');
        }
    }
}